//
//  GameViewController.m
//  Tapper
//
//  Created by iD Student on 7/10/13.
//  Copyright (c) 2013 iD Student. All rights reserved.
//

#import "GameViewController.h"

@interface GameViewController ()

@end

@implementation GameViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)loadGame
{
    timeRemaining = 60;
    score = 0;
    if(enemyList2 == nil)
    {
        enemyList2 = [[NSMutableArray alloc] initWithCapacity:0];
    }
    else
{
    [enemyList2 removeAllObjects];
    gameTimer = [NSTimer scheduledTimerWithTimeInterval:.25 target:self selector:@selector(gameUpdate) userInfo:nil repeats:true];
    scoreLabel.text = @"Score: 0";
}
}


-(void) gameUpdate
{
    if(timeRemaining <= 0)
    {
        [self gameOver];
    }
    timeRemaining -= .25;
    if (timeRemaining % 2 == 0)
    {
        Enemy *enemy = [[Enemy alloc] init];
        enemy.imageView.center = CGPointMake (arc4random() % 280 + 20, arc4random() % 400 + 20);
        [enemyList2 addObject:enemy];
        [self.view addSubview:enemy.imageView];
        
        int count = self.view.subviews.count;
        count = count;
    }
    int i =0;
    while (i<[enemyList2 count])
    {
        Enemy *enemy = [enemyList2 objectAtIndex:i];
        if(enemy.alive == false)
        {
            [enemy.imageView removeFromSuperview];
            [enemyList2 removeObject:enemy];
        }
        else{
            i++;
        }
        
    }
}

-(void) gameOver
{
    [gameTimer invalidate];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Game Over!" message:[NSString stringWithFormat:@"You scored %d", score] delegate:self cancelButtonTitle:@"Main Menu" otherButtonTitles: nil];
    [alert show];
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    for(Enemy *enemy in enemyList2)
    {
        if(CGRectContainsPoint(enemy.imageView.frame, touchPoint))
        {
            if(enemy.alive == true)
            {
                enemy.alive=false;
                score += enemy.pointValue;
                scoreLabel.text = [NSString stringWithFormat:@"Score: %d",score];
            }
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
